const Koa = require('koa');
const route = require('koa-route');
const app = new Koa();
const net = require('net');
const socket = new net.Socket();
var netpkg = require("./netpkg");
const port = 7777;
const hostname = '127.0.0.1';
let isConnect = false

function pack(json) {
  return netpkg.package(json)
}


function initSocket(data) {
  socket.setEncoding = 'UTF-8';

  socket.connect(port, hostname, function () {
    isConnect = true;

    socket.write(pack(data));
  });

  socket.on('data', function (msg) {
    console.log(msg);
  });

  socket.on('error', function (error) {
    isConnect = false;
    console.log('error' + error);
  });

  socket.on('close', function () {
    isConnect = false;
    console.log('服务器端下线了');
  });

}

const socketInit = ctx => {
  ctx.response.body = 'qqqq';

  // initSocket();



};



const send = ctx => {
  const query = ctx.request.query;
  console.log(`什么内容过来`, query);
  // ctx.body = { name: body.name };
  ctx.body = query;


  // console.log("打包数据呢", pack({ ID: 1, DataLen: 5, Data: "hello" }))
  // socket.write(pack({ ID: 1, DataLen: 5, Data: "hello" }));
  if (isConnect == false) {
    initSocket(query);
  } else {
    socket.write(pack(query));
  }
  // ID: 1, DataLen: 5, Data: "hello" 
};



const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(route.get('/', main));
app.use(route.get('/socketInit', socketInit));
app.use(route.get('/send', send));

app.use(main);
app.listen(3000);
console.log(`服务器运行在：3000`);